package Sms

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/mojocn/base64Captcha"
	"log"
	"project05_web/src/cache"
	"project05_web/src/global"
	"time"
)

// myType,1代表注册，2代表登录
func SendSMS(mobile string, myType int) (string, error) {
	// 生成6位随机Code
	driver := base64Captcha.NewDriverDigit(80, 240, 5, 0.7, 80)

	cp := base64Captcha.NewCaptcha(driver, cache.RedisStore{})

	id, _, code, err := cp.Generate()

	//添加验证码类别为手机号
	if myType == 1 {
		id = fmt.Sprintf("%s&amp%s", id, "phonetoregister")
	} else {
		id = fmt.Sprintf("%s&amp%s", id, "phonetologin")
	}

	//将id和手机号绑定
	res := global.RedisDb.Set(context.Background(), mobile, id, 2*time.Minute)
	if res.Err() != nil {
		log.Fatal("存储手机验证码失败")
		return "", res.Err()
	}
	// 通过accessKey Id和Secret连接服务，需要ID和密钥
	client, err := dysmsapi.NewClientWithAccessKey("cn-jiangxi", "AccessKeyID", "AccessKeySecret")
	if err != nil {
		log.Fatal("发送短信验证码失败")
		return "", err
	}
	request := dysmsapi.CreateSendSmsRequest() //创建请求
	request.Method = "POST"
	request.Scheme = "http"                   //请求协议，可选：https，但会慢一点
	request.PhoneNumbers = mobile             //接收短信的手机号码
	request.SignName = "your_signature"       //短信签名名称
	request.TemplateCode = "your_template_id" //短信模板ID
	Param, err := json.Marshal(map[string]interface{}{
		"code": code, // 验证码参数
	})
	if err != nil {
		return "", err
	}
	request.TemplateParam = string(Param) //将短信模板参数传入短信模板
	resp, err := client.SendSms(request)  //调用阿里云API发送信息
	if err != nil {
		return "", err
	}
	fmt.Println(resp)

	return code, nil
}
